Merge "Adding a bunch of hooks from wikiHow into DifferenceEngine, 2nd try"
[lhc/web/wiklou.git] / includes / filerepo / file / LocalFile.php
1 <?php
2 /**
3 * Local file in the wiki's own database.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileAbstraction
22 */
23
24 use \MediaWiki\Logger\LoggerFactory;
25
26 /**
27 * Bump this number when serialized cache records may be incompatible.
28 */
29 define( 'MW_FILE_VERSION', 9 );
30
31 /**
32 * Class to represent a local file in the wiki's own database
33 *
34 * Provides methods to retrieve paths (physical, logical, URL),
35 * to generate image thumbnails or for uploading.
36 *
37 * Note that only the repo object knows what its file class is called. You should
38 * never name a file class explictly outside of the repo class. Instead use the
39 * repo's factory functions to generate file objects, for example:
40 *
41 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
42 *
43 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * in most cases.
45 *
46 * @ingroup FileAbstraction
47 */
48 class LocalFile extends File {
49 const CACHE_FIELD_MAX_LEN = 1000;
50
51 /** @var bool Does the file exist on disk? (loadFromXxx) */
52 protected $fileExists;
53
54 /** @var int Image width */
55 protected $width;
56
57 /** @var int Image height */
58 protected $height;
59
60 /** @var int Returned by getimagesize (loadFromXxx) */
61 protected $bits;
62
63 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
64 protected $media_type;
65
66 /** @var string MIME type, determined by MimeMagic::guessMimeType */
67 protected $mime;
68
69 /** @var int Size in bytes (loadFromXxx) */
70 protected $size;
71
72 /** @var string Handler-specific metadata */
73 protected $metadata;
74
75 /** @var string SHA-1 base 36 content hash */
76 protected $sha1;
77
78 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
79 protected $dataLoaded;
80
81 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
82 protected $extraDataLoaded;
83
84 /** @var int Bitfield akin to rev_deleted */
85 protected $deleted;
86
87 /** @var string */
88 protected $repoClass = 'LocalRepo';
89
90 /** @var int Number of line to return by nextHistoryLine() (constructor) */
91 private $historyLine;
92
93 /** @var int Result of the query for the file's history (nextHistoryLine) */
94 private $historyRes;
95
96 /** @var string Major MIME type */
97 private $major_mime;
98
99 /** @var string Minor MIME type */
100 private $minor_mime;
101
102 /** @var string Upload timestamp */
103 private $timestamp;
104
105 /** @var int User ID of uploader */
106 private $user;
107
108 /** @var string User name of uploader */
109 private $user_text;
110
111 /** @var string Description of current revision of the file */
112 private $description;
113
114 /** @var string TS_MW timestamp of the last change of the file description */
115 private $descriptionTouched;
116
117 /** @var bool Whether the row was upgraded on load */
118 private $upgraded;
119
120 /** @var bool True if the image row is locked */
121 private $locked;
122
123 /** @var bool True if the image row is locked with a lock initiated transaction */
124 private $lockedOwnTrx;
125
126 /** @var bool True if file is not present in file system. Not to be cached in memcached */
127 private $missing;
128
129 // @note: higher than IDBAccessObject constants
130 const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
131
132 const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
133
134 /**
135 * Create a LocalFile from a title
136 * Do not call this except from inside a repo class.
137 *
138 * Note: $unused param is only here to avoid an E_STRICT
139 *
140 * @param Title $title
141 * @param FileRepo $repo
142 * @param null $unused
143 *
144 * @return LocalFile
145 */
146 static function newFromTitle( $title, $repo, $unused = null ) {
147 return new self( $title, $repo );
148 }
149
150 /**
151 * Create a LocalFile from a title
152 * Do not call this except from inside a repo class.
153 *
154 * @param stdClass $row
155 * @param FileRepo $repo
156 *
157 * @return LocalFile
158 */
159 static function newFromRow( $row, $repo ) {
160 $title = Title::makeTitle( NS_FILE, $row->img_name );
161 $file = new self( $title, $repo );
162 $file->loadFromRow( $row );
163
164 return $file;
165 }
166
167 /**
168 * Create a LocalFile from a SHA-1 key
169 * Do not call this except from inside a repo class.
170 *
171 * @param string $sha1 Base-36 SHA-1
172 * @param LocalRepo $repo
173 * @param string|bool $timestamp MW_timestamp (optional)
174 * @return bool|LocalFile
175 */
176 static function newFromKey( $sha1, $repo, $timestamp = false ) {
177 $dbr = $repo->getSlaveDB();
178
179 $conds = [ 'img_sha1' => $sha1 ];
180 if ( $timestamp ) {
181 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
182 }
183
184 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
185 if ( $row ) {
186 return self::newFromRow( $row, $repo );
187 } else {
188 return false;
189 }
190 }
191
192 /**
193 * Fields in the image table
194 * @return array
195 */
196 static function selectFields() {
197 return [
198 'img_name',
199 'img_size',
200 'img_width',
201 'img_height',
202 'img_metadata',
203 'img_bits',
204 'img_media_type',
205 'img_major_mime',
206 'img_minor_mime',
207 'img_description',
208 'img_user',
209 'img_user_text',
210 'img_timestamp',
211 'img_sha1',
212 ];
213 }
214
215 /**
216 * Constructor.
217 * Do not call this except from inside a repo class.
218 * @param Title $title
219 * @param FileRepo $repo
220 */
221 function __construct( $title, $repo ) {
222 parent::__construct( $title, $repo );
223
224 $this->metadata = '';
225 $this->historyLine = 0;
226 $this->historyRes = null;
227 $this->dataLoaded = false;
228 $this->extraDataLoaded = false;
229
230 $this->assertRepoDefined();
231 $this->assertTitleDefined();
232 }
233
234 /**
235 * Get the memcached key for the main data for this file, or false if
236 * there is no access to the shared cache.
237 * @return string|bool
238 */
239 function getCacheKey() {
240 $hashedName = md5( $this->getName() );
241
242 return $this->repo->getSharedCacheKey( 'file', $hashedName );
243 }
244
245 /**
246 * Try to load file metadata from memcached. Returns true on success.
247 * @return bool
248 */
249 private function loadFromCache() {
250 $this->dataLoaded = false;
251 $this->extraDataLoaded = false;
252 $key = $this->getCacheKey();
253
254 if ( !$key ) {
255 return false;
256 }
257
258 $cache = ObjectCache::getMainWANInstance();
259 $cachedValues = $cache->get( $key );
260
261 // Check if the key existed and belongs to this version of MediaWiki
262 if ( is_array( $cachedValues ) && $cachedValues['version'] == MW_FILE_VERSION ) {
263 $this->fileExists = $cachedValues['fileExists'];
264 if ( $this->fileExists ) {
265 $this->setProps( $cachedValues );
266 }
267 $this->dataLoaded = true;
268 $this->extraDataLoaded = true;
269 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
270 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
271 }
272 }
273
274 return $this->dataLoaded;
275 }
276
277 /**
278 * Save the file metadata to memcached
279 */
280 private function saveToCache() {
281 $this->load();
282
283 $key = $this->getCacheKey();
284 if ( !$key ) {
285 return;
286 }
287
288 $fields = $this->getCacheFields( '' );
289 $cacheVal = [ 'version' => MW_FILE_VERSION ];
290 $cacheVal['fileExists'] = $this->fileExists;
291
292 if ( $this->fileExists ) {
293 foreach ( $fields as $field ) {
294 $cacheVal[$field] = $this->$field;
295 }
296 }
297
298 // Strip off excessive entries from the subset of fields that can become large.
299 // If the cache value gets to large it will not fit in memcached and nothing will
300 // get cached at all, causing master queries for any file access.
301 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
302 if ( isset( $cacheVal[$field] ) && strlen( $cacheVal[$field] ) > 100 * 1024 ) {
303 unset( $cacheVal[$field] ); // don't let the value get too big
304 }
305 }
306
307 // Cache presence for 1 week and negatives for 1 day
308 $ttl = $this->fileExists ? 86400 * 7 : 86400;
309 $opts = Database::getCacheSetOptions( $this->repo->getSlaveDB() );
310 ObjectCache::getMainWANInstance()->set( $key, $cacheVal, $ttl, $opts );
311 }
312
313 /**
314 * Purge the file object/metadata cache
315 */
316 public function invalidateCache() {
317 $key = $this->getCacheKey();
318 if ( !$key ) {
319 return;
320 }
321
322 $this->repo->getMasterDB()->onTransactionPreCommitOrIdle( function() use ( $key ) {
323 ObjectCache::getMainWANInstance()->delete( $key );
324 } );
325 }
326
327 /**
328 * Load metadata from the file itself
329 */
330 function loadFromFile() {
331 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
332 $this->setProps( $props );
333 }
334
335 /**
336 * @param string $prefix
337 * @return array
338 */
339 function getCacheFields( $prefix = 'img_' ) {
340 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
341 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
342 'user_text', 'description' ];
343 static $results = [];
344
345 if ( $prefix == '' ) {
346 return $fields;
347 }
348
349 if ( !isset( $results[$prefix] ) ) {
350 $prefixedFields = [];
351 foreach ( $fields as $field ) {
352 $prefixedFields[] = $prefix . $field;
353 }
354 $results[$prefix] = $prefixedFields;
355 }
356
357 return $results[$prefix];
358 }
359
360 /**
361 * @param string $prefix
362 * @return array
363 */
364 function getLazyCacheFields( $prefix = 'img_' ) {
365 static $fields = [ 'metadata' ];
366 static $results = [];
367
368 if ( $prefix == '' ) {
369 return $fields;
370 }
371
372 if ( !isset( $results[$prefix] ) ) {
373 $prefixedFields = [];
374 foreach ( $fields as $field ) {
375 $prefixedFields[] = $prefix . $field;
376 }
377 $results[$prefix] = $prefixedFields;
378 }
379
380 return $results[$prefix];
381 }
382
383 /**
384 * Load file metadata from the DB
385 * @param int $flags
386 */
387 function loadFromDB( $flags = 0 ) {
388 $fname = get_class( $this ) . '::' . __FUNCTION__;
389
390 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
391 $this->dataLoaded = true;
392 $this->extraDataLoaded = true;
393
394 $dbr = ( $flags & self::READ_LATEST )
395 ? $this->repo->getMasterDB()
396 : $this->repo->getSlaveDB();
397
398 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
399 [ 'img_name' => $this->getName() ], $fname );
400
401 if ( $row ) {
402 $this->loadFromRow( $row );
403 } else {
404 $this->fileExists = false;
405 }
406 }
407
408 /**
409 * Load lazy file metadata from the DB.
410 * This covers fields that are sometimes not cached.
411 */
412 protected function loadExtraFromDB() {
413 $fname = get_class( $this ) . '::' . __FUNCTION__;
414
415 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
416 $this->extraDataLoaded = true;
417
418 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getSlaveDB(), $fname );
419 if ( !$fieldMap ) {
420 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getMasterDB(), $fname );
421 }
422
423 if ( $fieldMap ) {
424 foreach ( $fieldMap as $name => $value ) {
425 $this->$name = $value;
426 }
427 } else {
428 throw new MWException( "Could not find data for image '{$this->getName()}'." );
429 }
430 }
431
432 /**
433 * @param IDatabase $dbr
434 * @param string $fname
435 * @return array|bool
436 */
437 private function loadFieldsWithTimestamp( $dbr, $fname ) {
438 $fieldMap = false;
439
440 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
441 [ 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ],
442 $fname );
443 if ( $row ) {
444 $fieldMap = $this->unprefixRow( $row, 'img_' );
445 } else {
446 # File may have been uploaded over in the meantime; check the old versions
447 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
448 [ 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ],
449 $fname );
450 if ( $row ) {
451 $fieldMap = $this->unprefixRow( $row, 'oi_' );
452 }
453 }
454
455 return $fieldMap;
456 }
457
458 /**
459 * @param array|object $row
460 * @param string $prefix
461 * @throws MWException
462 * @return array
463 */
464 protected function unprefixRow( $row, $prefix = 'img_' ) {
465 $array = (array)$row;
466 $prefixLength = strlen( $prefix );
467
468 // Sanity check prefix once
469 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
470 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
471 }
472
473 $decoded = [];
474 foreach ( $array as $name => $value ) {
475 $decoded[substr( $name, $prefixLength )] = $value;
476 }
477
478 return $decoded;
479 }
480
481 /**
482 * Decode a row from the database (either object or array) to an array
483 * with timestamps and MIME types decoded, and the field prefix removed.
484 * @param object $row
485 * @param string $prefix
486 * @throws MWException
487 * @return array
488 */
489 function decodeRow( $row, $prefix = 'img_' ) {
490 $decoded = $this->unprefixRow( $row, $prefix );
491
492 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
493
494 $decoded['metadata'] = $this->repo->getSlaveDB()->decodeBlob( $decoded['metadata'] );
495
496 if ( empty( $decoded['major_mime'] ) ) {
497 $decoded['mime'] = 'unknown/unknown';
498 } else {
499 if ( !$decoded['minor_mime'] ) {
500 $decoded['minor_mime'] = 'unknown';
501 }
502 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
503 }
504
505 // Trim zero padding from char/binary field
506 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
507
508 // Normalize some fields to integer type, per their database definition.
509 // Use unary + so that overflows will be upgraded to double instead of
510 // being trucated as with intval(). This is important to allow >2GB
511 // files on 32-bit systems.
512 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
513 $decoded[$field] = +$decoded[$field];
514 }
515
516 return $decoded;
517 }
518
519 /**
520 * Load file metadata from a DB result row
521 *
522 * @param object $row
523 * @param string $prefix
524 */
525 function loadFromRow( $row, $prefix = 'img_' ) {
526 $this->dataLoaded = true;
527 $this->extraDataLoaded = true;
528
529 $array = $this->decodeRow( $row, $prefix );
530
531 foreach ( $array as $name => $value ) {
532 $this->$name = $value;
533 }
534
535 $this->fileExists = true;
536 $this->maybeUpgradeRow();
537 }
538
539 /**
540 * Load file metadata from cache or DB, unless already loaded
541 * @param int $flags
542 */
543 function load( $flags = 0 ) {
544 if ( !$this->dataLoaded ) {
545 if ( ( $flags & self::READ_LATEST ) || !$this->loadFromCache() ) {
546 $this->loadFromDB( $flags );
547 $this->saveToCache();
548 }
549 $this->dataLoaded = true;
550 }
551 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
552 // @note: loads on name/timestamp to reduce race condition problems
553 $this->loadExtraFromDB();
554 }
555 }
556
557 /**
558 * Upgrade a row if it needs it
559 */
560 function maybeUpgradeRow() {
561 global $wgUpdateCompatibleMetadata;
562 if ( wfReadOnly() ) {
563 return;
564 }
565
566 $upgrade = false;
567 if ( is_null( $this->media_type ) ||
568 $this->mime == 'image/svg'
569 ) {
570 $upgrade = true;
571 } else {
572 $handler = $this->getHandler();
573 if ( $handler ) {
574 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
575 if ( $validity === MediaHandler::METADATA_BAD
576 || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
577 ) {
578 $upgrade = true;
579 }
580 }
581 }
582
583 if ( $upgrade ) {
584 try {
585 $this->upgradeRow();
586 } catch ( LocalFileLockError $e ) {
587 // let the other process handle it (or do it next time)
588 }
589 $this->upgraded = true; // avoid rework/retries
590 }
591 }
592
593 function getUpgraded() {
594 return $this->upgraded;
595 }
596
597 /**
598 * Fix assorted version-related problems with the image row by reloading it from the file
599 */
600 function upgradeRow() {
601 $this->lock(); // begin
602
603 $this->loadFromFile();
604
605 # Don't destroy file info of missing files
606 if ( !$this->fileExists ) {
607 $this->unlock();
608 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
609
610 return;
611 }
612
613 $dbw = $this->repo->getMasterDB();
614 list( $major, $minor ) = self::splitMime( $this->mime );
615
616 if ( wfReadOnly() ) {
617 $this->unlock();
618
619 return;
620 }
621 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
622
623 $dbw->update( 'image',
624 [
625 'img_size' => $this->size, // sanity
626 'img_width' => $this->width,
627 'img_height' => $this->height,
628 'img_bits' => $this->bits,
629 'img_media_type' => $this->media_type,
630 'img_major_mime' => $major,
631 'img_minor_mime' => $minor,
632 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
633 'img_sha1' => $this->sha1,
634 ],
635 [ 'img_name' => $this->getName() ],
636 __METHOD__
637 );
638
639 $this->invalidateCache();
640
641 $this->unlock(); // done
642
643 }
644
645 /**
646 * Set properties in this object to be equal to those given in the
647 * associative array $info. Only cacheable fields can be set.
648 * All fields *must* be set in $info except for getLazyCacheFields().
649 *
650 * If 'mime' is given, it will be split into major_mime/minor_mime.
651 * If major_mime/minor_mime are given, $this->mime will also be set.
652 *
653 * @param array $info
654 */
655 function setProps( $info ) {
656 $this->dataLoaded = true;
657 $fields = $this->getCacheFields( '' );
658 $fields[] = 'fileExists';
659
660 foreach ( $fields as $field ) {
661 if ( isset( $info[$field] ) ) {
662 $this->$field = $info[$field];
663 }
664 }
665
666 // Fix up mime fields
667 if ( isset( $info['major_mime'] ) ) {
668 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
669 } elseif ( isset( $info['mime'] ) ) {
670 $this->mime = $info['mime'];
671 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
672 }
673 }
674
675 /** splitMime inherited */
676 /** getName inherited */
677 /** getTitle inherited */
678 /** getURL inherited */
679 /** getViewURL inherited */
680 /** getPath inherited */
681 /** isVisible inherited */
682
683 /**
684 * @return bool
685 */
686 function isMissing() {
687 if ( $this->missing === null ) {
688 list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
689 $this->missing = !$fileExists;
690 }
691
692 return $this->missing;
693 }
694
695 /**
696 * Return the width of the image
697 *
698 * @param int $page
699 * @return int
700 */
701 public function getWidth( $page = 1 ) {
702 $this->load();
703
704 if ( $this->isMultipage() ) {
705 $handler = $this->getHandler();
706 if ( !$handler ) {
707 return 0;
708 }
709 $dim = $handler->getPageDimensions( $this, $page );
710 if ( $dim ) {
711 return $dim['width'];
712 } else {
713 // For non-paged media, the false goes through an
714 // intval, turning failure into 0, so do same here.
715 return 0;
716 }
717 } else {
718 return $this->width;
719 }
720 }
721
722 /**
723 * Return the height of the image
724 *
725 * @param int $page
726 * @return int
727 */
728 public function getHeight( $page = 1 ) {
729 $this->load();
730
731 if ( $this->isMultipage() ) {
732 $handler = $this->getHandler();
733 if ( !$handler ) {
734 return 0;
735 }
736 $dim = $handler->getPageDimensions( $this, $page );
737 if ( $dim ) {
738 return $dim['height'];
739 } else {
740 // For non-paged media, the false goes through an
741 // intval, turning failure into 0, so do same here.
742 return 0;
743 }
744 } else {
745 return $this->height;
746 }
747 }
748
749 /**
750 * Returns ID or name of user who uploaded the file
751 *
752 * @param string $type 'text' or 'id'
753 * @return int|string
754 */
755 function getUser( $type = 'text' ) {
756 $this->load();
757
758 if ( $type == 'text' ) {
759 return $this->user_text;
760 } elseif ( $type == 'id' ) {
761 return (int)$this->user;
762 }
763 }
764
765 /**
766 * Get short description URL for a file based on the page ID.
767 *
768 * @return string|null
769 * @throws MWException
770 * @since 1.27
771 */
772 public function getDescriptionShortUrl() {
773 $pageId = $this->title->getArticleID();
774
775 if ( $pageId !== null ) {
776 $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
777 if ( $url !== false ) {
778 return $url;
779 }
780 }
781 return null;
782 }
783
784 /**
785 * Get handler-specific metadata
786 * @return string
787 */
788 function getMetadata() {
789 $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
790 return $this->metadata;
791 }
792
793 /**
794 * @return int
795 */
796 function getBitDepth() {
797 $this->load();
798
799 return (int)$this->bits;
800 }
801
802 /**
803 * Returns the size of the image file, in bytes
804 * @return int
805 */
806 public function getSize() {
807 $this->load();
808
809 return $this->size;
810 }
811
812 /**
813 * Returns the MIME type of the file.
814 * @return string
815 */
816 function getMimeType() {
817 $this->load();
818
819 return $this->mime;
820 }
821
822 /**
823 * Returns the type of the media in the file.
824 * Use the value returned by this function with the MEDIATYPE_xxx constants.
825 * @return string
826 */
827 function getMediaType() {
828 $this->load();
829
830 return $this->media_type;
831 }
832
833 /** canRender inherited */
834 /** mustRender inherited */
835 /** allowInlineDisplay inherited */
836 /** isSafeFile inherited */
837 /** isTrustedFile inherited */
838
839 /**
840 * Returns true if the file exists on disk.
841 * @return bool Whether file exist on disk.
842 */
843 public function exists() {
844 $this->load();
845
846 return $this->fileExists;
847 }
848
849 /** getTransformScript inherited */
850 /** getUnscaledThumb inherited */
851 /** thumbName inherited */
852 /** createThumb inherited */
853 /** transform inherited */
854
855 /** getHandler inherited */
856 /** iconThumb inherited */
857 /** getLastError inherited */
858
859 /**
860 * Get all thumbnail names previously generated for this file
861 * @param string|bool $archiveName Name of an archive file, default false
862 * @return array First element is the base dir, then files in that base dir.
863 */
864 function getThumbnails( $archiveName = false ) {
865 if ( $archiveName ) {
866 $dir = $this->getArchiveThumbPath( $archiveName );
867 } else {
868 $dir = $this->getThumbPath();
869 }
870
871 $backend = $this->repo->getBackend();
872 $files = [ $dir ];
873 try {
874 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
875 foreach ( $iterator as $file ) {
876 $files[] = $file;
877 }
878 } catch ( FileBackendError $e ) {
879 } // suppress (bug 54674)
880
881 return $files;
882 }
883
884 /**
885 * Refresh metadata in memcached, but don't touch thumbnails or CDN
886 */
887 function purgeMetadataCache() {
888 $this->invalidateCache();
889 }
890
891 /**
892 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
893 *
894 * @param array $options An array potentially with the key forThumbRefresh.
895 *
896 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
897 */
898 function purgeCache( $options = [] ) {
899 // Refresh metadata cache
900 $this->purgeMetadataCache();
901
902 // Delete thumbnails
903 $this->purgeThumbnails( $options );
904
905 // Purge CDN cache for this file
906 DeferredUpdates::addUpdate(
907 new CdnCacheUpdate( [ $this->getUrl() ] ),
908 DeferredUpdates::PRESEND
909 );
910 }
911
912 /**
913 * Delete cached transformed files for an archived version only.
914 * @param string $archiveName Name of the archived file
915 */
916 function purgeOldThumbnails( $archiveName ) {
917 // Get a list of old thumbnails and URLs
918 $files = $this->getThumbnails( $archiveName );
919
920 // Purge any custom thumbnail caches
921 Hooks::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
922
923 // Delete thumbnails
924 $dir = array_shift( $files );
925 $this->purgeThumbList( $dir, $files );
926
927 // Purge the CDN
928 $urls = [];
929 foreach ( $files as $file ) {
930 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
931 }
932 DeferredUpdates::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates::PRESEND );
933 }
934
935 /**
936 * Delete cached transformed files for the current version only.
937 * @param array $options
938 */
939 public function purgeThumbnails( $options = [] ) {
940 $files = $this->getThumbnails();
941 // Always purge all files from CDN regardless of handler filters
942 $urls = [];
943 foreach ( $files as $file ) {
944 $urls[] = $this->getThumbUrl( $file );
945 }
946 array_shift( $urls ); // don't purge directory
947
948 // Give media handler a chance to filter the file purge list
949 if ( !empty( $options['forThumbRefresh'] ) ) {
950 $handler = $this->getHandler();
951 if ( $handler ) {
952 $handler->filterThumbnailPurgeList( $files, $options );
953 }
954 }
955
956 // Purge any custom thumbnail caches
957 Hooks::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
958
959 // Delete thumbnails
960 $dir = array_shift( $files );
961 $this->purgeThumbList( $dir, $files );
962
963 // Purge the CDN
964 DeferredUpdates::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates::PRESEND );
965 }
966
967 /**
968 * Delete a list of thumbnails visible at urls
969 * @param string $dir Base dir of the files.
970 * @param array $files Array of strings: relative filenames (to $dir)
971 */
972 protected function purgeThumbList( $dir, $files ) {
973 $fileListDebug = strtr(
974 var_export( $files, true ),
975 [ "\n" => '' ]
976 );
977 wfDebug( __METHOD__ . ": $fileListDebug\n" );
978
979 $purgeList = [];
980 foreach ( $files as $file ) {
981 # Check that the base file name is part of the thumb name
982 # This is a basic sanity check to avoid erasing unrelated directories
983 if ( strpos( $file, $this->getName() ) !== false
984 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
985 ) {
986 $purgeList[] = "{$dir}/{$file}";
987 }
988 }
989
990 # Delete the thumbnails
991 $this->repo->quickPurgeBatch( $purgeList );
992 # Clear out the thumbnail directory if empty
993 $this->repo->quickCleanDir( $dir );
994 }
995
996 /** purgeDescription inherited */
997 /** purgeEverything inherited */
998
999 /**
1000 * @param int $limit Optional: Limit to number of results
1001 * @param int $start Optional: Timestamp, start from
1002 * @param int $end Optional: Timestamp, end at
1003 * @param bool $inc
1004 * @return OldLocalFile[]
1005 */
1006 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1007 $dbr = $this->repo->getSlaveDB();
1008 $tables = [ 'oldimage' ];
1009 $fields = OldLocalFile::selectFields();
1010 $conds = $opts = $join_conds = [];
1011 $eq = $inc ? '=' : '';
1012 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1013
1014 if ( $start ) {
1015 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1016 }
1017
1018 if ( $end ) {
1019 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1020 }
1021
1022 if ( $limit ) {
1023 $opts['LIMIT'] = $limit;
1024 }
1025
1026 // Search backwards for time > x queries
1027 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1028 $opts['ORDER BY'] = "oi_timestamp $order";
1029 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1030
1031 Hooks::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields,
1032 &$conds, &$opts, &$join_conds ] );
1033
1034 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1035 $r = [];
1036
1037 foreach ( $res as $row ) {
1038 $r[] = $this->repo->newFileFromRow( $row );
1039 }
1040
1041 if ( $order == 'ASC' ) {
1042 $r = array_reverse( $r ); // make sure it ends up descending
1043 }
1044
1045 return $r;
1046 }
1047
1048 /**
1049 * Returns the history of this file, line by line.
1050 * starts with current version, then old versions.
1051 * uses $this->historyLine to check which line to return:
1052 * 0 return line for current version
1053 * 1 query for old versions, return first one
1054 * 2, ... return next old version from above query
1055 * @return bool
1056 */
1057 public function nextHistoryLine() {
1058 # Polymorphic function name to distinguish foreign and local fetches
1059 $fname = get_class( $this ) . '::' . __FUNCTION__;
1060
1061 $dbr = $this->repo->getSlaveDB();
1062
1063 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1064 $this->historyRes = $dbr->select( 'image',
1065 [
1066 '*',
1067 "'' AS oi_archive_name",
1068 '0 as oi_deleted',
1069 'img_sha1'
1070 ],
1071 [ 'img_name' => $this->title->getDBkey() ],
1072 $fname
1073 );
1074
1075 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1076 $this->historyRes = null;
1077
1078 return false;
1079 }
1080 } elseif ( $this->historyLine == 1 ) {
1081 $this->historyRes = $dbr->select( 'oldimage', '*',
1082 [ 'oi_name' => $this->title->getDBkey() ],
1083 $fname,
1084 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1085 );
1086 }
1087 $this->historyLine++;
1088
1089 return $dbr->fetchObject( $this->historyRes );
1090 }
1091
1092 /**
1093 * Reset the history pointer to the first element of the history
1094 */
1095 public function resetHistory() {
1096 $this->historyLine = 0;
1097
1098 if ( !is_null( $this->historyRes ) ) {
1099 $this->historyRes = null;
1100 }
1101 }
1102
1103 /** getHashPath inherited */
1104 /** getRel inherited */
1105 /** getUrlRel inherited */
1106 /** getArchiveRel inherited */
1107 /** getArchivePath inherited */
1108 /** getThumbPath inherited */
1109 /** getArchiveUrl inherited */
1110 /** getThumbUrl inherited */
1111 /** getArchiveVirtualUrl inherited */
1112 /** getThumbVirtualUrl inherited */
1113 /** isHashed inherited */
1114
1115 /**
1116 * Upload a file and record it in the DB
1117 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1118 * @param string $comment Upload description
1119 * @param string $pageText Text to use for the new description page,
1120 * if a new description page is created
1121 * @param int|bool $flags Flags for publish()
1122 * @param array|bool $props File properties, if known. This can be used to
1123 * reduce the upload time when uploading virtual URLs for which the file
1124 * info is already known
1125 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1126 * current time
1127 * @param User|null $user User object or null to use $wgUser
1128 * @param string[] $tags Change tags to add to the log entry and page revision.
1129 * (This doesn't check $user's permissions.)
1130 * @return FileRepoStatus On success, the value member contains the
1131 * archive name, or an empty string if it was a new file.
1132 */
1133 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1134 $timestamp = false, $user = null, $tags = []
1135 ) {
1136 global $wgContLang;
1137
1138 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1139 return $this->readOnlyFatalStatus();
1140 }
1141
1142 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1143 if ( !$props ) {
1144 if ( $this->repo->isVirtualUrl( $srcPath )
1145 || FileBackend::isStoragePath( $srcPath )
1146 ) {
1147 $props = $this->repo->getFileProps( $srcPath );
1148 } else {
1149 $props = FSFile::getPropsFromPath( $srcPath );
1150 }
1151 }
1152
1153 $options = [];
1154 $handler = MediaHandler::getHandler( $props['mime'] );
1155 if ( $handler ) {
1156 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1157 } else {
1158 $options['headers'] = [];
1159 }
1160
1161 // Trim spaces on user supplied text
1162 $comment = trim( $comment );
1163
1164 // Truncate nicely or the DB will do it for us
1165 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1166 $comment = $wgContLang->truncate( $comment, 255 );
1167 $this->lock(); // begin
1168 $status = $this->publish( $src, $flags, $options );
1169
1170 if ( $status->successCount >= 2 ) {
1171 // There will be a copy+(one of move,copy,store).
1172 // The first succeeding does not commit us to updating the DB
1173 // since it simply copied the current version to a timestamped file name.
1174 // It is only *preferable* to avoid leaving such files orphaned.
1175 // Once the second operation goes through, then the current version was
1176 // updated and we must therefore update the DB too.
1177 $oldver = $status->value;
1178 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1179 $status->fatal( 'filenotfound', $srcPath );
1180 }
1181 }
1182
1183 $this->unlock(); // done
1184
1185 return $status;
1186 }
1187
1188 /**
1189 * Record a file upload in the upload log and the image table
1190 * @param string $oldver
1191 * @param string $desc
1192 * @param string $license
1193 * @param string $copyStatus
1194 * @param string $source
1195 * @param bool $watch
1196 * @param string|bool $timestamp
1197 * @param User|null $user User object or null to use $wgUser
1198 * @return bool
1199 */
1200 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1201 $watch = false, $timestamp = false, User $user = null ) {
1202 if ( !$user ) {
1203 global $wgUser;
1204 $user = $wgUser;
1205 }
1206
1207 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1208
1209 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1210 return false;
1211 }
1212
1213 if ( $watch ) {
1214 $user->addWatch( $this->getTitle() );
1215 }
1216
1217 return true;
1218 }
1219
1220 /**
1221 * Record a file upload in the upload log and the image table
1222 * @param string $oldver
1223 * @param string $comment
1224 * @param string $pageText
1225 * @param bool|array $props
1226 * @param string|bool $timestamp
1227 * @param null|User $user
1228 * @param string[] $tags
1229 * @return bool
1230 */
1231 function recordUpload2(
1232 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1233 ) {
1234 if ( is_null( $user ) ) {
1235 global $wgUser;
1236 $user = $wgUser;
1237 }
1238
1239 $dbw = $this->repo->getMasterDB();
1240
1241 # Imports or such might force a certain timestamp; otherwise we generate
1242 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1243 if ( $timestamp === false ) {
1244 $timestamp = $dbw->timestamp();
1245 $allowTimeKludge = true;
1246 } else {
1247 $allowTimeKludge = false;
1248 }
1249
1250 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1251 $props['description'] = $comment;
1252 $props['user'] = $user->getId();
1253 $props['user_text'] = $user->getName();
1254 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1255 $this->setProps( $props );
1256
1257 # Fail now if the file isn't there
1258 if ( !$this->fileExists ) {
1259 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1260
1261 return false;
1262 }
1263
1264 $dbw->startAtomic( __METHOD__ );
1265
1266 # Test to see if the row exists using INSERT IGNORE
1267 # This avoids race conditions by locking the row until the commit, and also
1268 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1269 $dbw->insert( 'image',
1270 [
1271 'img_name' => $this->getName(),
1272 'img_size' => $this->size,
1273 'img_width' => intval( $this->width ),
1274 'img_height' => intval( $this->height ),
1275 'img_bits' => $this->bits,
1276 'img_media_type' => $this->media_type,
1277 'img_major_mime' => $this->major_mime,
1278 'img_minor_mime' => $this->minor_mime,
1279 'img_timestamp' => $timestamp,
1280 'img_description' => $comment,
1281 'img_user' => $user->getId(),
1282 'img_user_text' => $user->getName(),
1283 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1284 'img_sha1' => $this->sha1
1285 ],
1286 __METHOD__,
1287 'IGNORE'
1288 );
1289
1290 $reupload = ( $dbw->affectedRows() == 0 );
1291 if ( $reupload ) {
1292 if ( $allowTimeKludge ) {
1293 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1294 $ltimestamp = $dbw->selectField(
1295 'image',
1296 'img_timestamp',
1297 [ 'img_name' => $this->getName() ],
1298 __METHOD__,
1299 [ 'LOCK IN SHARE MODE' ]
1300 );
1301 $lUnixtime = $ltimestamp ? wfTimestamp( TS_UNIX, $ltimestamp ) : false;
1302 # Avoid a timestamp that is not newer than the last version
1303 # TODO: the image/oldimage tables should be like page/revision with an ID field
1304 if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1305 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1306 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1307 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1308 }
1309 }
1310
1311 # (bug 34993) Note: $oldver can be empty here, if the previous
1312 # version of the file was broken. Allow registration of the new
1313 # version to continue anyway, because that's better than having
1314 # an image that's not fixable by user operations.
1315 # Collision, this is an update of a file
1316 # Insert previous contents into oldimage
1317 $dbw->insertSelect( 'oldimage', 'image',
1318 [
1319 'oi_name' => 'img_name',
1320 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1321 'oi_size' => 'img_size',
1322 'oi_width' => 'img_width',
1323 'oi_height' => 'img_height',
1324 'oi_bits' => 'img_bits',
1325 'oi_timestamp' => 'img_timestamp',
1326 'oi_description' => 'img_description',
1327 'oi_user' => 'img_user',
1328 'oi_user_text' => 'img_user_text',
1329 'oi_metadata' => 'img_metadata',
1330 'oi_media_type' => 'img_media_type',
1331 'oi_major_mime' => 'img_major_mime',
1332 'oi_minor_mime' => 'img_minor_mime',
1333 'oi_sha1' => 'img_sha1'
1334 ],
1335 [ 'img_name' => $this->getName() ],
1336 __METHOD__
1337 );
1338
1339 # Update the current image row
1340 $dbw->update( 'image',
1341 [
1342 'img_size' => $this->size,
1343 'img_width' => intval( $this->width ),
1344 'img_height' => intval( $this->height ),
1345 'img_bits' => $this->bits,
1346 'img_media_type' => $this->media_type,
1347 'img_major_mime' => $this->major_mime,
1348 'img_minor_mime' => $this->minor_mime,
1349 'img_timestamp' => $timestamp,
1350 'img_description' => $comment,
1351 'img_user' => $user->getId(),
1352 'img_user_text' => $user->getName(),
1353 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1354 'img_sha1' => $this->sha1
1355 ],
1356 [ 'img_name' => $this->getName() ],
1357 __METHOD__
1358 );
1359 }
1360
1361 $descTitle = $this->getTitle();
1362 $descId = $descTitle->getArticleID();
1363 $wikiPage = new WikiFilePage( $descTitle );
1364 $wikiPage->setFile( $this );
1365
1366 // Add the log entry...
1367 $logEntry = new ManualLogEntry( 'upload', $reupload ? 'overwrite' : 'upload' );
1368 $logEntry->setTimestamp( $this->timestamp );
1369 $logEntry->setPerformer( $user );
1370 $logEntry->setComment( $comment );
1371 $logEntry->setTarget( $descTitle );
1372 // Allow people using the api to associate log entries with the upload.
1373 // Log has a timestamp, but sometimes different from upload timestamp.
1374 $logEntry->setParameters(
1375 [
1376 'img_sha1' => $this->sha1,
1377 'img_timestamp' => $timestamp,
1378 ]
1379 );
1380 // Note we keep $logId around since during new image
1381 // creation, page doesn't exist yet, so log_page = 0
1382 // but we want it to point to the page we're making,
1383 // so we later modify the log entry.
1384 // For a similar reason, we avoid making an RC entry
1385 // now and wait until the page exists.
1386 $logId = $logEntry->insert();
1387
1388 if ( $descTitle->exists() ) {
1389 // Use own context to get the action text in content language
1390 $formatter = LogFormatter::newFromEntry( $logEntry );
1391 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1392 $editSummary = $formatter->getPlainActionText();
1393
1394 $nullRevision = Revision::newNullRevision(
1395 $dbw,
1396 $descId,
1397 $editSummary,
1398 false,
1399 $user
1400 );
1401 if ( $nullRevision ) {
1402 $nullRevision->insertOn( $dbw );
1403 Hooks::run(
1404 'NewRevisionFromEditComplete',
1405 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1406 );
1407 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1408 // Associate null revision id
1409 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1410 }
1411
1412 $newPageContent = null;
1413 } else {
1414 // Make the description page and RC log entry post-commit
1415 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1416 }
1417
1418 # Defer purges, page creation, and link updates in case they error out.
1419 # The most important thing is that files and the DB registry stay synced.
1420 $dbw->endAtomic( __METHOD__ );
1421
1422 # Do some cache purges after final commit so that:
1423 # a) Changes are more likely to be seen post-purge
1424 # b) They won't cause rollback of the log publish/update above
1425 DeferredUpdates::addUpdate(
1426 new AutoCommitUpdate(
1427 $dbw,
1428 __METHOD__,
1429 function () use (
1430 $reupload, $wikiPage, $newPageContent, $comment, $user,
1431 $logEntry, $logId, $descId, $tags
1432 ) {
1433 # Update memcache after the commit
1434 $this->invalidateCache();
1435
1436 $updateLogPage = false;
1437 if ( $newPageContent ) {
1438 # New file page; create the description page.
1439 # There's already a log entry, so don't make a second RC entry
1440 # CDN and file cache for the description page are purged by doEditContent.
1441 $status = $wikiPage->doEditContent(
1442 $newPageContent,
1443 $comment,
1444 EDIT_NEW | EDIT_SUPPRESS_RC,
1445 false,
1446 $user
1447 );
1448
1449 if ( isset( $status->value['revision'] ) ) {
1450 // Associate new page revision id
1451 $logEntry->setAssociatedRevId( $status->value['revision']->getId() );
1452 }
1453 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1454 // which is triggered on $descTitle by doEditContent() above.
1455 if ( isset( $status->value['revision'] ) ) {
1456 /** @var $rev Revision */
1457 $rev = $status->value['revision'];
1458 $updateLogPage = $rev->getPage();
1459 }
1460 } else {
1461 # Existing file page: invalidate description page cache
1462 $wikiPage->getTitle()->invalidateCache();
1463 $wikiPage->getTitle()->purgeSquid();
1464 # Allow the new file version to be patrolled from the page footer
1465 Article::purgePatrolFooterCache( $descId );
1466 }
1467
1468 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1469 # but setAssociatedRevId() wasn't called at that point yet...
1470 $logParams = $logEntry->getParameters();
1471 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1472 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1473 if ( $updateLogPage ) {
1474 # Also log page, in case where we just created it above
1475 $update['log_page'] = $updateLogPage;
1476 }
1477 $this->getRepo()->getMasterDB()->update(
1478 'logging',
1479 $update,
1480 [ 'log_id' => $logId ],
1481 __METHOD__
1482 );
1483 $this->getRepo()->getMasterDB()->insert(
1484 'log_search',
1485 [
1486 'ls_field' => 'associated_rev_id',
1487 'ls_value' => $logEntry->getAssociatedRevId(),
1488 'ls_log_id' => $logId,
1489 ],
1490 __METHOD__
1491 );
1492
1493 # Add change tags, if any
1494 if ( $tags ) {
1495 $logEntry->setTags( $tags );
1496 }
1497
1498 # Uploads can be patrolled
1499 $logEntry->setIsPatrollable( true );
1500
1501 # Now that the log entry is up-to-date, make an RC entry.
1502 $logEntry->publish( $logId );
1503
1504 # Run hook for other updates (typically more cache purging)
1505 Hooks::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1506
1507 if ( $reupload ) {
1508 # Delete old thumbnails
1509 $this->purgeThumbnails();
1510 # Remove the old file from the CDN cache
1511 DeferredUpdates::addUpdate(
1512 new CdnCacheUpdate( [ $this->getUrl() ] ),
1513 DeferredUpdates::PRESEND
1514 );
1515 } else {
1516 # Update backlink pages pointing to this title if created
1517 LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1518 }
1519 }
1520 ),
1521 DeferredUpdates::PRESEND
1522 );
1523
1524 if ( !$reupload ) {
1525 # This is a new file, so update the image count
1526 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1527 }
1528
1529 # Invalidate cache for all pages using this file
1530 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1531
1532 return true;
1533 }
1534
1535 /**
1536 * Move or copy a file to its public location. If a file exists at the
1537 * destination, move it to an archive. Returns a FileRepoStatus object with
1538 * the archive name in the "value" member on success.
1539 *
1540 * The archive name should be passed through to recordUpload for database
1541 * registration.
1542 *
1543 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1544 * @param int $flags A bitwise combination of:
1545 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1546 * @param array $options Optional additional parameters
1547 * @return FileRepoStatus On success, the value member contains the
1548 * archive name, or an empty string if it was a new file.
1549 */
1550 function publish( $src, $flags = 0, array $options = [] ) {
1551 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1552 }
1553
1554 /**
1555 * Move or copy a file to a specified location. Returns a FileRepoStatus
1556 * object with the archive name in the "value" member on success.
1557 *
1558 * The archive name should be passed through to recordUpload for database
1559 * registration.
1560 *
1561 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1562 * @param string $dstRel Target relative path
1563 * @param int $flags A bitwise combination of:
1564 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1565 * @param array $options Optional additional parameters
1566 * @return FileRepoStatus On success, the value member contains the
1567 * archive name, or an empty string if it was a new file.
1568 */
1569 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1570 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1571
1572 $repo = $this->getRepo();
1573 if ( $repo->getReadOnlyReason() !== false ) {
1574 return $this->readOnlyFatalStatus();
1575 }
1576
1577 $this->lock(); // begin
1578
1579 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1580 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1581
1582 if ( $repo->hasSha1Storage() ) {
1583 $sha1 = $repo->isVirtualUrl( $srcPath )
1584 ? $repo->getFileSha1( $srcPath )
1585 : FSFile::getSha1Base36FromPath( $srcPath );
1586 $dst = $repo->getBackend()->getPathForSHA1( $sha1 );
1587 $status = $repo->quickImport( $src, $dst );
1588 if ( $flags & File::DELETE_SOURCE ) {
1589 unlink( $srcPath );
1590 }
1591
1592 if ( $this->exists() ) {
1593 $status->value = $archiveName;
1594 }
1595 } else {
1596 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1597 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1598
1599 if ( $status->value == 'new' ) {
1600 $status->value = '';
1601 } else {
1602 $status->value = $archiveName;
1603 }
1604 }
1605
1606 $this->unlock(); // done
1607
1608 return $status;
1609 }
1610
1611 /** getLinksTo inherited */
1612 /** getExifData inherited */
1613 /** isLocal inherited */
1614 /** wasDeleted inherited */
1615
1616 /**
1617 * Move file to the new title
1618 *
1619 * Move current, old version and all thumbnails
1620 * to the new filename. Old file is deleted.
1621 *
1622 * Cache purging is done; checks for validity
1623 * and logging are caller's responsibility
1624 *
1625 * @param Title $target New file name
1626 * @return FileRepoStatus
1627 */
1628 function move( $target ) {
1629 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1630 return $this->readOnlyFatalStatus();
1631 }
1632
1633 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1634 $batch = new LocalFileMoveBatch( $this, $target );
1635
1636 $this->lock(); // begin
1637 $batch->addCurrent();
1638 $archiveNames = $batch->addOlds();
1639 $status = $batch->execute();
1640 $this->unlock(); // done
1641
1642 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1643
1644 // Purge the source and target files...
1645 $oldTitleFile = wfLocalFile( $this->title );
1646 $newTitleFile = wfLocalFile( $target );
1647 // To avoid slow purges in the transaction, move them outside...
1648 DeferredUpdates::addUpdate(
1649 new AutoCommitUpdate(
1650 $this->getRepo()->getMasterDB(),
1651 __METHOD__,
1652 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1653 $oldTitleFile->purgeEverything();
1654 foreach ( $archiveNames as $archiveName ) {
1655 $oldTitleFile->purgeOldThumbnails( $archiveName );
1656 }
1657 $newTitleFile->purgeEverything();
1658 }
1659 ),
1660 DeferredUpdates::PRESEND
1661 );
1662
1663 if ( $status->isOK() ) {
1664 // Now switch the object
1665 $this->title = $target;
1666 // Force regeneration of the name and hashpath
1667 unset( $this->name );
1668 unset( $this->hashPath );
1669 }
1670
1671 return $status;
1672 }
1673
1674 /**
1675 * Delete all versions of the file.
1676 *
1677 * Moves the files into an archive directory (or deletes them)
1678 * and removes the database rows.
1679 *
1680 * Cache purging is done; logging is caller's responsibility.
1681 *
1682 * @param string $reason
1683 * @param bool $suppress
1684 * @param User|null $user
1685 * @return FileRepoStatus
1686 */
1687 function delete( $reason, $suppress = false, $user = null ) {
1688 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1689 return $this->readOnlyFatalStatus();
1690 }
1691
1692 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1693
1694 $this->lock(); // begin
1695 $batch->addCurrent();
1696 // Get old version relative paths
1697 $archiveNames = $batch->addOlds();
1698 $status = $batch->execute();
1699 $this->unlock(); // done
1700
1701 if ( $status->isOK() ) {
1702 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
1703 }
1704
1705 // To avoid slow purges in the transaction, move them outside...
1706 DeferredUpdates::addUpdate(
1707 new AutoCommitUpdate(
1708 $this->getRepo()->getMasterDB(),
1709 __METHOD__,
1710 function () use ( $archiveNames ) {
1711 $this->purgeEverything();
1712 foreach ( $archiveNames as $archiveName ) {
1713 $this->purgeOldThumbnails( $archiveName );
1714 }
1715 }
1716 ),
1717 DeferredUpdates::PRESEND
1718 );
1719
1720 // Purge the CDN
1721 $purgeUrls = [];
1722 foreach ( $archiveNames as $archiveName ) {
1723 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1724 }
1725 DeferredUpdates::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
1726
1727 return $status;
1728 }
1729
1730 /**
1731 * Delete an old version of the file.
1732 *
1733 * Moves the file into an archive directory (or deletes it)
1734 * and removes the database row.
1735 *
1736 * Cache purging is done; logging is caller's responsibility.
1737 *
1738 * @param string $archiveName
1739 * @param string $reason
1740 * @param bool $suppress
1741 * @param User|null $user
1742 * @throws MWException Exception on database or file store failure
1743 * @return FileRepoStatus
1744 */
1745 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1746 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1747 return $this->readOnlyFatalStatus();
1748 }
1749
1750 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1751
1752 $this->lock(); // begin
1753 $batch->addOld( $archiveName );
1754 $status = $batch->execute();
1755 $this->unlock(); // done
1756
1757 $this->purgeOldThumbnails( $archiveName );
1758 if ( $status->isOK() ) {
1759 $this->purgeDescription();
1760 }
1761
1762 DeferredUpdates::addUpdate(
1763 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1764 DeferredUpdates::PRESEND
1765 );
1766
1767 return $status;
1768 }
1769
1770 /**
1771 * Restore all or specified deleted revisions to the given file.
1772 * Permissions and logging are left to the caller.
1773 *
1774 * May throw database exceptions on error.
1775 *
1776 * @param array $versions Set of record ids of deleted items to restore,
1777 * or empty to restore all revisions.
1778 * @param bool $unsuppress
1779 * @return FileRepoStatus
1780 */
1781 function restore( $versions = [], $unsuppress = false ) {
1782 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1783 return $this->readOnlyFatalStatus();
1784 }
1785
1786 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1787
1788 $this->lock(); // begin
1789 if ( !$versions ) {
1790 $batch->addAll();
1791 } else {
1792 $batch->addIds( $versions );
1793 }
1794 $status = $batch->execute();
1795 if ( $status->isGood() ) {
1796 $cleanupStatus = $batch->cleanup();
1797 $cleanupStatus->successCount = 0;
1798 $cleanupStatus->failCount = 0;
1799 $status->merge( $cleanupStatus );
1800 }
1801 $this->unlock(); // done
1802
1803 return $status;
1804 }
1805
1806 /** isMultipage inherited */
1807 /** pageCount inherited */
1808 /** scaleHeight inherited */
1809 /** getImageSize inherited */
1810
1811 /**
1812 * Get the URL of the file description page.
1813 * @return string
1814 */
1815 function getDescriptionUrl() {
1816 return $this->title->getLocalURL();
1817 }
1818
1819 /**
1820 * Get the HTML text of the description page
1821 * This is not used by ImagePage for local files, since (among other things)
1822 * it skips the parser cache.
1823 *
1824 * @param Language $lang What language to get description in (Optional)
1825 * @return bool|mixed
1826 */
1827 function getDescriptionText( $lang = null ) {
1828 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1829 if ( !$revision ) {
1830 return false;
1831 }
1832 $content = $revision->getContent();
1833 if ( !$content ) {
1834 return false;
1835 }
1836 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1837
1838 return $pout->getText();
1839 }
1840
1841 /**
1842 * @param int $audience
1843 * @param User $user
1844 * @return string
1845 */
1846 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1847 $this->load();
1848 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
1849 return '';
1850 } elseif ( $audience == self::FOR_THIS_USER
1851 && !$this->userCan( self::DELETED_COMMENT, $user )
1852 ) {
1853 return '';
1854 } else {
1855 return $this->description;
1856 }
1857 }
1858
1859 /**
1860 * @return bool|string
1861 */
1862 function getTimestamp() {
1863 $this->load();
1864
1865 return $this->timestamp;
1866 }
1867
1868 /**
1869 * @return bool|string
1870 */
1871 public function getDescriptionTouched() {
1872 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1873 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1874 // need to differentiate between null (uninitialized) and false (failed to load).
1875 if ( $this->descriptionTouched === null ) {
1876 $cond = [
1877 'page_namespace' => $this->title->getNamespace(),
1878 'page_title' => $this->title->getDBkey()
1879 ];
1880 $touched = $this->repo->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
1881 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
1882 }
1883
1884 return $this->descriptionTouched;
1885 }
1886
1887 /**
1888 * @return string
1889 */
1890 function getSha1() {
1891 $this->load();
1892 // Initialise now if necessary
1893 if ( $this->sha1 == '' && $this->fileExists ) {
1894 $this->lock(); // begin
1895
1896 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1897 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1898 $dbw = $this->repo->getMasterDB();
1899 $dbw->update( 'image',
1900 [ 'img_sha1' => $this->sha1 ],
1901 [ 'img_name' => $this->getName() ],
1902 __METHOD__ );
1903 $this->invalidateCache();
1904 }
1905
1906 $this->unlock(); // done
1907 }
1908
1909 return $this->sha1;
1910 }
1911
1912 /**
1913 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1914 */
1915 function isCacheable() {
1916 $this->load();
1917
1918 // If extra data (metadata) was not loaded then it must have been large
1919 return $this->extraDataLoaded
1920 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1921 }
1922
1923 /**
1924 * @return Status
1925 * @since 1.28
1926 */
1927 public function acquireFileLock() {
1928 return $this->getRepo()->getBackend()->lockFiles(
1929 [ $this->getPath() ], LockManager::LOCK_EX, 10
1930 );
1931 }
1932
1933 /**
1934 * @return Status
1935 * @since 1.28
1936 */
1937 public function releaseFileLock() {
1938 return $this->getRepo()->getBackend()->unlockFiles(
1939 [ $this->getPath() ], LockManager::LOCK_EX
1940 );
1941 }
1942
1943 /**
1944 * Start an atomic DB section and lock the image for update
1945 * or increments a reference counter if the lock is already held
1946 *
1947 * This method should not be used outside of LocalFile/LocalFile*Batch
1948 *
1949 * @throws LocalFileLockError Throws an error if the lock was not acquired
1950 * @return bool Whether the file lock owns/spawned the DB transaction
1951 */
1952 public function lock() {
1953 if ( !$this->locked ) {
1954 $logger = LoggerFactory::getInstance( 'LocalFile' );
1955
1956 $dbw = $this->repo->getMasterDB();
1957 $makesTransaction = !$dbw->trxLevel();
1958 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
1959 // Bug 54736: use simple lock to handle when the file does not exist.
1960 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1961 // Also, that would cause contention on INSERT of similarly named rows.
1962 $status = $this->acquireFileLock(); // represents all versions of the file
1963 if ( !$status->isGood() ) {
1964 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
1965 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
1966
1967 throw new LocalFileLockError( $status );
1968 }
1969 // Release the lock *after* commit to avoid row-level contention.
1970 // Make sure it triggers on rollback() as well as commit() (T132921).
1971 $dbw->onTransactionResolution( function () use ( $logger ) {
1972 $status = $this->releaseFileLock();
1973 if ( !$status->isGood() ) {
1974 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
1975 }
1976 } );
1977 // Callers might care if the SELECT snapshot is safely fresh
1978 $this->lockedOwnTrx = $makesTransaction;
1979 }
1980
1981 $this->locked++;
1982
1983 return $this->lockedOwnTrx;
1984 }
1985
1986 /**
1987 * Decrement the lock reference count and end the atomic section if it reaches zero
1988 *
1989 * This method should not be used outside of LocalFile/LocalFile*Batch
1990 *
1991 * The commit and loc release will happen when no atomic sections are active, which
1992 * may happen immediately or at some point after calling this
1993 */
1994 public function unlock() {
1995 if ( $this->locked ) {
1996 --$this->locked;
1997 if ( !$this->locked ) {
1998 $dbw = $this->repo->getMasterDB();
1999 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2000 $this->lockedOwnTrx = false;
2001 }
2002 }
2003 }
2004
2005 /**
2006 * @return Status
2007 */
2008 protected function readOnlyFatalStatus() {
2009 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2010 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2011 }
2012
2013 /**
2014 * Clean up any dangling locks
2015 */
2016 function __destruct() {
2017 $this->unlock();
2018 }
2019 } // LocalFile class
2020
2021 # ------------------------------------------------------------------------------
2022
2023 /**
2024 * Helper class for file deletion
2025 * @ingroup FileAbstraction
2026 */
2027 class LocalFileDeleteBatch {
2028 /** @var LocalFile */
2029 private $file;
2030
2031 /** @var string */
2032 private $reason;
2033
2034 /** @var array */
2035 private $srcRels = [];
2036
2037 /** @var array */
2038 private $archiveUrls = [];
2039
2040 /** @var array Items to be processed in the deletion batch */
2041 private $deletionBatch;
2042
2043 /** @var bool Whether to suppress all suppressable fields when deleting */
2044 private $suppress;
2045
2046 /** @var FileRepoStatus */
2047 private $status;
2048
2049 /** @var User */
2050 private $user;
2051
2052 /**
2053 * @param File $file
2054 * @param string $reason
2055 * @param bool $suppress
2056 * @param User|null $user
2057 */
2058 function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
2059 $this->file = $file;
2060 $this->reason = $reason;
2061 $this->suppress = $suppress;
2062 if ( $user ) {
2063 $this->user = $user;
2064 } else {
2065 global $wgUser;
2066 $this->user = $wgUser;
2067 }
2068 $this->status = $file->repo->newGood();
2069 }
2070
2071 public function addCurrent() {
2072 $this->srcRels['.'] = $this->file->getRel();
2073 }
2074
2075 /**
2076 * @param string $oldName
2077 */
2078 public function addOld( $oldName ) {
2079 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2080 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2081 }
2082
2083 /**
2084 * Add the old versions of the image to the batch
2085 * @return array List of archive names from old versions
2086 */
2087 public function addOlds() {
2088 $archiveNames = [];
2089
2090 $dbw = $this->file->repo->getMasterDB();
2091 $result = $dbw->select( 'oldimage',
2092 [ 'oi_archive_name' ],
2093 [ 'oi_name' => $this->file->getName() ],
2094 __METHOD__
2095 );
2096
2097 foreach ( $result as $row ) {
2098 $this->addOld( $row->oi_archive_name );
2099 $archiveNames[] = $row->oi_archive_name;
2100 }
2101
2102 return $archiveNames;
2103 }
2104
2105 /**
2106 * @return array
2107 */
2108 protected function getOldRels() {
2109 if ( !isset( $this->srcRels['.'] ) ) {
2110 $oldRels =& $this->srcRels;
2111 $deleteCurrent = false;
2112 } else {
2113 $oldRels = $this->srcRels;
2114 unset( $oldRels['.'] );
2115 $deleteCurrent = true;
2116 }
2117
2118 return [ $oldRels, $deleteCurrent ];
2119 }
2120
2121 /**
2122 * @return array
2123 */
2124 protected function getHashes() {
2125 $hashes = [];
2126 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2127
2128 if ( $deleteCurrent ) {
2129 $hashes['.'] = $this->file->getSha1();
2130 }
2131
2132 if ( count( $oldRels ) ) {
2133 $dbw = $this->file->repo->getMasterDB();
2134 $res = $dbw->select(
2135 'oldimage',
2136 [ 'oi_archive_name', 'oi_sha1' ],
2137 [ 'oi_archive_name' => array_keys( $oldRels ),
2138 'oi_name' => $this->file->getName() ], // performance
2139 __METHOD__
2140 );
2141
2142 foreach ( $res as $row ) {
2143 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2144 // Get the hash from the file
2145 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2146 $props = $this->file->repo->getFileProps( $oldUrl );
2147
2148 if ( $props['fileExists'] ) {
2149 // Upgrade the oldimage row
2150 $dbw->update( 'oldimage',
2151 [ 'oi_sha1' => $props['sha1'] ],
2152 [ 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ],
2153 __METHOD__ );
2154 $hashes[$row->oi_archive_name] = $props['sha1'];
2155 } else {
2156 $hashes[$row->oi_archive_name] = false;
2157 }
2158 } else {
2159 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2160 }
2161 }
2162 }
2163
2164 $missing = array_diff_key( $this->srcRels, $hashes );
2165
2166 foreach ( $missing as $name => $rel ) {
2167 $this->status->error( 'filedelete-old-unregistered', $name );
2168 }
2169
2170 foreach ( $hashes as $name => $hash ) {
2171 if ( !$hash ) {
2172 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2173 unset( $hashes[$name] );
2174 }
2175 }
2176
2177 return $hashes;
2178 }
2179
2180 protected function doDBInserts() {
2181 $dbw = $this->file->repo->getMasterDB();
2182 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2183 $encUserId = $dbw->addQuotes( $this->user->getId() );
2184 $encReason = $dbw->addQuotes( $this->reason );
2185 $encGroup = $dbw->addQuotes( 'deleted' );
2186 $ext = $this->file->getExtension();
2187 $dotExt = $ext === '' ? '' : ".$ext";
2188 $encExt = $dbw->addQuotes( $dotExt );
2189 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2190
2191 // Bitfields to further suppress the content
2192 if ( $this->suppress ) {
2193 $bitfield = 0;
2194 // This should be 15...
2195 $bitfield |= Revision::DELETED_TEXT;
2196 $bitfield |= Revision::DELETED_COMMENT;
2197 $bitfield |= Revision::DELETED_USER;
2198 $bitfield |= Revision::DELETED_RESTRICTED;
2199 } else {
2200 $bitfield = 'oi_deleted';
2201 }
2202
2203 if ( $deleteCurrent ) {
2204 $concat = $dbw->buildConcat( [ "img_sha1", $encExt ] );
2205 $where = [ 'img_name' => $this->file->getName() ];
2206 $dbw->insertSelect( 'filearchive', 'image',
2207 [
2208 'fa_storage_group' => $encGroup,
2209 'fa_storage_key' => $dbw->conditional(
2210 [ 'img_sha1' => '' ],
2211 $dbw->addQuotes( '' ),
2212 $concat
2213 ),
2214 'fa_deleted_user' => $encUserId,
2215 'fa_deleted_timestamp' => $encTimestamp,
2216 'fa_deleted_reason' => $encReason,
2217 'fa_deleted' => $this->suppress ? $bitfield : 0,
2218
2219 'fa_name' => 'img_name',
2220 'fa_archive_name' => 'NULL',
2221 'fa_size' => 'img_size',
2222 'fa_width' => 'img_width',
2223 'fa_height' => 'img_height',
2224 'fa_metadata' => 'img_metadata',
2225 'fa_bits' => 'img_bits',
2226 'fa_media_type' => 'img_media_type',
2227 'fa_major_mime' => 'img_major_mime',
2228 'fa_minor_mime' => 'img_minor_mime',
2229 'fa_description' => 'img_description',
2230 'fa_user' => 'img_user',
2231 'fa_user_text' => 'img_user_text',
2232 'fa_timestamp' => 'img_timestamp',
2233 'fa_sha1' => 'img_sha1',
2234 ], $where, __METHOD__ );
2235 }
2236
2237 if ( count( $oldRels ) ) {
2238 $concat = $dbw->buildConcat( [ "oi_sha1", $encExt ] );
2239 $where = [
2240 'oi_name' => $this->file->getName(),
2241 'oi_archive_name' => array_keys( $oldRels ) ];
2242 $dbw->insertSelect( 'filearchive', 'oldimage',
2243 [
2244 'fa_storage_group' => $encGroup,
2245 'fa_storage_key' => $dbw->conditional(
2246 [ 'oi_sha1' => '' ],
2247 $dbw->addQuotes( '' ),
2248 $concat
2249 ),
2250 'fa_deleted_user' => $encUserId,
2251 'fa_deleted_timestamp' => $encTimestamp,
2252 'fa_deleted_reason' => $encReason,
2253 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
2254
2255 'fa_name' => 'oi_name',
2256 'fa_archive_name' => 'oi_archive_name',
2257 'fa_size' => 'oi_size',
2258 'fa_width' => 'oi_width',
2259 'fa_height' => 'oi_height',
2260 'fa_metadata' => 'oi_metadata',
2261 'fa_bits' => 'oi_bits',
2262 'fa_media_type' => 'oi_media_type',
2263 'fa_major_mime' => 'oi_major_mime',
2264 'fa_minor_mime' => 'oi_minor_mime',
2265 'fa_description' => 'oi_description',
2266 'fa_user' => 'oi_user',
2267 'fa_user_text' => 'oi_user_text',
2268 'fa_timestamp' => 'oi_timestamp',
2269 'fa_sha1' => 'oi_sha1',
2270 ], $where, __METHOD__ );
2271 }
2272 }
2273
2274 function doDBDeletes() {
2275 $dbw = $this->file->repo->getMasterDB();
2276 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2277
2278 if ( count( $oldRels ) ) {
2279 $dbw->delete( 'oldimage',
2280 [
2281 'oi_name' => $this->file->getName(),
2282 'oi_archive_name' => array_keys( $oldRels )
2283 ], __METHOD__ );
2284 }
2285
2286 if ( $deleteCurrent ) {
2287 $dbw->delete( 'image', [ 'img_name' => $this->file->getName() ], __METHOD__ );
2288 }
2289 }
2290
2291 /**
2292 * Run the transaction
2293 * @return FileRepoStatus
2294 */
2295 public function execute() {
2296 $repo = $this->file->getRepo();
2297 $this->file->lock();
2298
2299 // Prepare deletion batch
2300 $hashes = $this->getHashes();
2301 $this->deletionBatch = [];
2302 $ext = $this->file->getExtension();
2303 $dotExt = $ext === '' ? '' : ".$ext";
2304
2305 foreach ( $this->srcRels as $name => $srcRel ) {
2306 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2307 if ( isset( $hashes[$name] ) ) {
2308 $hash = $hashes[$name];
2309 $key = $hash . $dotExt;
2310 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2311 $this->deletionBatch[$name] = [ $srcRel, $dstRel ];
2312 }
2313 }
2314
2315 if ( !$repo->hasSha1Storage() ) {
2316 // Removes non-existent file from the batch, so we don't get errors.
2317 // This also handles files in the 'deleted' zone deleted via revision deletion.
2318 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2319 if ( !$checkStatus->isGood() ) {
2320 $this->status->merge( $checkStatus );
2321 return $this->status;
2322 }
2323 $this->deletionBatch = $checkStatus->value;
2324
2325 // Execute the file deletion batch
2326 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2327 if ( !$status->isGood() ) {
2328 $this->status->merge( $status );
2329 }
2330 }
2331
2332 if ( !$this->status->isOK() ) {
2333 // Critical file deletion error; abort
2334 $this->file->unlock();
2335
2336 return $this->status;
2337 }
2338
2339 // Copy the image/oldimage rows to filearchive
2340 $this->doDBInserts();
2341 // Delete image/oldimage rows
2342 $this->doDBDeletes();
2343
2344 // Commit and return
2345 $this->file->unlock();
2346
2347 return $this->status;
2348 }
2349
2350 /**
2351 * Removes non-existent files from a deletion batch.
2352 * @param array $batch
2353 * @return Status
2354 */
2355 protected function removeNonexistentFiles( $batch ) {
2356 $files = $newBatch = [];
2357
2358 foreach ( $batch as $batchItem ) {
2359 list( $src, ) = $batchItem;
2360 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2361 }
2362
2363 $result = $this->file->repo->fileExistsBatch( $files );
2364 if ( in_array( null, $result, true ) ) {
2365 return Status::newFatal( 'backend-fail-internal',
2366 $this->file->repo->getBackend()->getName() );
2367 }
2368
2369 foreach ( $batch as $batchItem ) {
2370 if ( $result[$batchItem[0]] ) {
2371 $newBatch[] = $batchItem;
2372 }
2373 }
2374
2375 return Status::newGood( $newBatch );
2376 }
2377 }
2378
2379 # ------------------------------------------------------------------------------
2380
2381 /**
2382 * Helper class for file undeletion
2383 * @ingroup FileAbstraction
2384 */
2385 class LocalFileRestoreBatch {
2386 /** @var LocalFile */
2387 private $file;
2388
2389 /** @var array List of file IDs to restore */
2390 private $cleanupBatch;
2391
2392 /** @var array List of file IDs to restore */
2393 private $ids;
2394
2395 /** @var bool Add all revisions of the file */
2396 private $all;
2397
2398 /** @var bool Whether to remove all settings for suppressed fields */
2399 private $unsuppress = false;
2400
2401 /**
2402 * @param File $file
2403 * @param bool $unsuppress
2404 */
2405 function __construct( File $file, $unsuppress = false ) {
2406 $this->file = $file;
2407 $this->cleanupBatch = $this->ids = [];
2408 $this->ids = [];
2409 $this->unsuppress = $unsuppress;
2410 }
2411
2412 /**
2413 * Add a file by ID
2414 * @param int $fa_id
2415 */
2416 public function addId( $fa_id ) {
2417 $this->ids[] = $fa_id;
2418 }
2419
2420 /**
2421 * Add a whole lot of files by ID
2422 * @param int[] $ids
2423 */
2424 public function addIds( $ids ) {
2425 $this->ids = array_merge( $this->ids, $ids );
2426 }
2427
2428 /**
2429 * Add all revisions of the file
2430 */
2431 public function addAll() {
2432 $this->all = true;
2433 }
2434
2435 /**
2436 * Run the transaction, except the cleanup batch.
2437 * The cleanup batch should be run in a separate transaction, because it locks different
2438 * rows and there's no need to keep the image row locked while it's acquiring those locks
2439 * The caller may have its own transaction open.
2440 * So we save the batch and let the caller call cleanup()
2441 * @return FileRepoStatus
2442 */
2443 public function execute() {
2444 global $wgLang;
2445
2446 $repo = $this->file->getRepo();
2447 if ( !$this->all && !$this->ids ) {
2448 // Do nothing
2449 return $repo->newGood();
2450 }
2451
2452 $lockOwnsTrx = $this->file->lock();
2453
2454 $dbw = $this->file->repo->getMasterDB();
2455 $status = $this->file->repo->newGood();
2456
2457 $exists = (bool)$dbw->selectField( 'image', '1',
2458 [ 'img_name' => $this->file->getName() ],
2459 __METHOD__,
2460 // The lock() should already prevents changes, but this still may need
2461 // to bypass any transaction snapshot. However, if lock() started the
2462 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2463 $lockOwnsTrx ? [] : [ 'LOCK IN SHARE MODE' ]
2464 );
2465
2466 // Fetch all or selected archived revisions for the file,
2467 // sorted from the most recent to the oldest.
2468 $conditions = [ 'fa_name' => $this->file->getName() ];
2469
2470 if ( !$this->all ) {
2471 $conditions['fa_id'] = $this->ids;
2472 }
2473
2474 $result = $dbw->select(
2475 'filearchive',
2476 ArchivedFile::selectFields(),
2477 $conditions,
2478 __METHOD__,
2479 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2480 );
2481
2482 $idsPresent = [];
2483 $storeBatch = [];
2484 $insertBatch = [];
2485 $insertCurrent = false;
2486 $deleteIds = [];
2487 $first = true;
2488 $archiveNames = [];
2489
2490 foreach ( $result as $row ) {
2491 $idsPresent[] = $row->fa_id;
2492
2493 if ( $row->fa_name != $this->file->getName() ) {
2494 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2495 $status->failCount++;
2496 continue;
2497 }
2498
2499 if ( $row->fa_storage_key == '' ) {
2500 // Revision was missing pre-deletion
2501 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2502 $status->failCount++;
2503 continue;
2504 }
2505
2506 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2507 $row->fa_storage_key;
2508 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2509
2510 if ( isset( $row->fa_sha1 ) ) {
2511 $sha1 = $row->fa_sha1;
2512 } else {
2513 // old row, populate from key
2514 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2515 }
2516
2517 # Fix leading zero
2518 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2519 $sha1 = substr( $sha1, 1 );
2520 }
2521
2522 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2523 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2524 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2525 || is_null( $row->fa_metadata )
2526 ) {
2527 // Refresh our metadata
2528 // Required for a new current revision; nice for older ones too. :)
2529 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2530 } else {
2531 $props = [
2532 'minor_mime' => $row->fa_minor_mime,
2533 'major_mime' => $row->fa_major_mime,
2534 'media_type' => $row->fa_media_type,
2535 'metadata' => $row->fa_metadata
2536 ];
2537 }
2538
2539 if ( $first && !$exists ) {
2540 // This revision will be published as the new current version
2541 $destRel = $this->file->getRel();
2542 $insertCurrent = [
2543 'img_name' => $row->fa_name,
2544 'img_size' => $row->fa_size,
2545 'img_width' => $row->fa_width,
2546 'img_height' => $row->fa_height,
2547 'img_metadata' => $props['metadata'],
2548 'img_bits' => $row->fa_bits,
2549 'img_media_type' => $props['media_type'],
2550 'img_major_mime' => $props['major_mime'],
2551 'img_minor_mime' => $props['minor_mime'],
2552 'img_description' => $row->fa_description,
2553 'img_user' => $row->fa_user,
2554 'img_user_text' => $row->fa_user_text,
2555 'img_timestamp' => $row->fa_timestamp,
2556 'img_sha1' => $sha1
2557 ];
2558
2559 // The live (current) version cannot be hidden!
2560 if ( !$this->unsuppress && $row->fa_deleted ) {
2561 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2562 $this->cleanupBatch[] = $row->fa_storage_key;
2563 }
2564 } else {
2565 $archiveName = $row->fa_archive_name;
2566
2567 if ( $archiveName == '' ) {
2568 // This was originally a current version; we
2569 // have to devise a new archive name for it.
2570 // Format is <timestamp of archiving>!<name>
2571 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2572
2573 do {
2574 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2575 $timestamp++;
2576 } while ( isset( $archiveNames[$archiveName] ) );
2577 }
2578
2579 $archiveNames[$archiveName] = true;
2580 $destRel = $this->file->getArchiveRel( $archiveName );
2581 $insertBatch[] = [
2582 'oi_name' => $row->fa_name,
2583 'oi_archive_name' => $archiveName,
2584 'oi_size' => $row->fa_size,
2585 'oi_width' => $row->fa_width,
2586 'oi_height' => $row->fa_height,
2587 'oi_bits' => $row->fa_bits,
2588 'oi_description' => $row->fa_description,
2589 'oi_user' => $row->fa_user,
2590 'oi_user_text' => $row->fa_user_text,
2591 'oi_timestamp' => $row->fa_timestamp,
2592 'oi_metadata' => $props['metadata'],
2593 'oi_media_type' => $props['media_type'],
2594 'oi_major_mime' => $props['major_mime'],
2595 'oi_minor_mime' => $props['minor_mime'],
2596 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2597 'oi_sha1' => $sha1 ];
2598 }
2599
2600 $deleteIds[] = $row->fa_id;
2601
2602 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2603 // private files can stay where they are
2604 $status->successCount++;
2605 } else {
2606 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2607 $this->cleanupBatch[] = $row->fa_storage_key;
2608 }
2609
2610 $first = false;
2611 }
2612
2613 unset( $result );
2614
2615 // Add a warning to the status object for missing IDs
2616 $missingIds = array_diff( $this->ids, $idsPresent );
2617
2618 foreach ( $missingIds as $id ) {
2619 $status->error( 'undelete-missing-filearchive', $id );
2620 }
2621
2622 if ( !$repo->hasSha1Storage() ) {
2623 // Remove missing files from batch, so we don't get errors when undeleting them
2624 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2625 if ( !$checkStatus->isGood() ) {
2626 $status->merge( $checkStatus );
2627 return $status;
2628 }
2629 $storeBatch = $checkStatus->value;
2630
2631 // Run the store batch
2632 // Use the OVERWRITE_SAME flag to smooth over a common error
2633 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2634 $status->merge( $storeStatus );
2635
2636 if ( !$status->isGood() ) {
2637 // Even if some files could be copied, fail entirely as that is the
2638 // easiest thing to do without data loss
2639 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2640 $status->ok = false;
2641 $this->file->unlock();
2642
2643 return $status;
2644 }
2645 }
2646
2647 // Run the DB updates
2648 // Because we have locked the image row, key conflicts should be rare.
2649 // If they do occur, we can roll back the transaction at this time with
2650 // no data loss, but leaving unregistered files scattered throughout the
2651 // public zone.
2652 // This is not ideal, which is why it's important to lock the image row.
2653 if ( $insertCurrent ) {
2654 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2655 }
2656
2657 if ( $insertBatch ) {
2658 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2659 }
2660
2661 if ( $deleteIds ) {
2662 $dbw->delete( 'filearchive',
2663 [ 'fa_id' => $deleteIds ],
2664 __METHOD__ );
2665 }
2666
2667 // If store batch is empty (all files are missing), deletion is to be considered successful
2668 if ( $status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
2669 if ( !$exists ) {
2670 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2671
2672 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2673
2674 $this->file->purgeEverything();
2675 } else {
2676 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2677 $this->file->purgeDescription();
2678 }
2679 }
2680
2681 $this->file->unlock();
2682
2683 return $status;
2684 }
2685
2686 /**
2687 * Removes non-existent files from a store batch.
2688 * @param array $triplets
2689 * @return Status
2690 */
2691 protected function removeNonexistentFiles( $triplets ) {
2692 $files = $filteredTriplets = [];
2693 foreach ( $triplets as $file ) {
2694 $files[$file[0]] = $file[0];
2695 }
2696
2697 $result = $this->file->repo->fileExistsBatch( $files );
2698 if ( in_array( null, $result, true ) ) {
2699 return Status::newFatal( 'backend-fail-internal',
2700 $this->file->repo->getBackend()->getName() );
2701 }
2702
2703 foreach ( $triplets as $file ) {
2704 if ( $result[$file[0]] ) {
2705 $filteredTriplets[] = $file;
2706 }
2707 }
2708
2709 return Status::newGood( $filteredTriplets );
2710 }
2711
2712 /**
2713 * Removes non-existent files from a cleanup batch.
2714 * @param array $batch
2715 * @return array
2716 */
2717 protected function removeNonexistentFromCleanup( $batch ) {
2718 $files = $newBatch = [];
2719 $repo = $this->file->repo;
2720
2721 foreach ( $batch as $file ) {
2722 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2723 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2724 }
2725
2726 $result = $repo->fileExistsBatch( $files );
2727
2728 foreach ( $batch as $file ) {
2729 if ( $result[$file] ) {
2730 $newBatch[] = $file;
2731 }
2732 }
2733
2734 return $newBatch;
2735 }
2736
2737 /**
2738 * Delete unused files in the deleted zone.
2739 * This should be called from outside the transaction in which execute() was called.
2740 * @return FileRepoStatus
2741 */
2742 public function cleanup() {
2743 if ( !$this->cleanupBatch ) {
2744 return $this->file->repo->newGood();
2745 }
2746
2747 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2748
2749 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2750
2751 return $status;
2752 }
2753
2754 /**
2755 * Cleanup a failed batch. The batch was only partially successful, so
2756 * rollback by removing all items that were succesfully copied.
2757 *
2758 * @param Status $storeStatus
2759 * @param array $storeBatch
2760 */
2761 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2762 $cleanupBatch = [];
2763
2764 foreach ( $storeStatus->success as $i => $success ) {
2765 // Check if this item of the batch was successfully copied
2766 if ( $success ) {
2767 // Item was successfully copied and needs to be removed again
2768 // Extract ($dstZone, $dstRel) from the batch
2769 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2770 }
2771 }
2772 $this->file->repo->cleanupBatch( $cleanupBatch );
2773 }
2774 }
2775
2776 # ------------------------------------------------------------------------------
2777
2778 /**
2779 * Helper class for file movement
2780 * @ingroup FileAbstraction
2781 */
2782 class LocalFileMoveBatch {
2783 /** @var LocalFile */
2784 protected $file;
2785
2786 /** @var Title */
2787 protected $target;
2788
2789 protected $cur;
2790
2791 protected $olds;
2792
2793 protected $oldCount;
2794
2795 protected $archive;
2796
2797 /** @var DatabaseBase */
2798 protected $db;
2799
2800 /**
2801 * @param File $file
2802 * @param Title $target
2803 */
2804 function __construct( File $file, Title $target ) {
2805 $this->file = $file;
2806 $this->target = $target;
2807 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2808 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2809 $this->oldName = $this->file->getName();
2810 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2811 $this->oldRel = $this->oldHash . $this->oldName;
2812 $this->newRel = $this->newHash . $this->newName;
2813 $this->db = $file->getRepo()->getMasterDB();
2814 }
2815
2816 /**
2817 * Add the current image to the batch
2818 */
2819 public function addCurrent() {
2820 $this->cur = [ $this->oldRel, $this->newRel ];
2821 }
2822
2823 /**
2824 * Add the old versions of the image to the batch
2825 * @return array List of archive names from old versions
2826 */
2827 public function addOlds() {
2828 $archiveBase = 'archive';
2829 $this->olds = [];
2830 $this->oldCount = 0;
2831 $archiveNames = [];
2832
2833 $result = $this->db->select( 'oldimage',
2834 [ 'oi_archive_name', 'oi_deleted' ],
2835 [ 'oi_name' => $this->oldName ],
2836 __METHOD__,
2837 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2838 );
2839
2840 foreach ( $result as $row ) {
2841 $archiveNames[] = $row->oi_archive_name;
2842 $oldName = $row->oi_archive_name;
2843 $bits = explode( '!', $oldName, 2 );
2844
2845 if ( count( $bits ) != 2 ) {
2846 wfDebug( "Old file name missing !: '$oldName' \n" );
2847 continue;
2848 }
2849
2850 list( $timestamp, $filename ) = $bits;
2851
2852 if ( $this->oldName != $filename ) {
2853 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2854 continue;
2855 }
2856
2857 $this->oldCount++;
2858
2859 // Do we want to add those to oldCount?
2860 if ( $row->oi_deleted & File::DELETED_FILE ) {
2861 continue;
2862 }
2863
2864 $this->olds[] = [
2865 "{$archiveBase}/{$this->oldHash}{$oldName}",
2866 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2867 ];
2868 }
2869
2870 return $archiveNames;
2871 }
2872
2873 /**
2874 * Perform the move.
2875 * @return FileRepoStatus
2876 */
2877 public function execute() {
2878 $repo = $this->file->repo;
2879 $status = $repo->newGood();
2880 $destFile = wfLocalFile( $this->target );
2881
2882 $this->file->lock(); // begin
2883 $destFile->lock(); // quickly fail if destination is not available
2884
2885 $triplets = $this->getMoveTriplets();
2886 $checkStatus = $this->removeNonexistentFiles( $triplets );
2887 if ( !$checkStatus->isGood() ) {
2888 $destFile->unlock();
2889 $this->file->unlock();
2890 $status->merge( $checkStatus ); // couldn't talk to file backend
2891 return $status;
2892 }
2893 $triplets = $checkStatus->value;
2894
2895 // Verify the file versions metadata in the DB.
2896 $statusDb = $this->verifyDBUpdates();
2897 if ( !$statusDb->isGood() ) {
2898 $destFile->unlock();
2899 $this->file->unlock();
2900 $statusDb->ok = false;
2901
2902 return $statusDb;
2903 }
2904
2905 if ( !$repo->hasSha1Storage() ) {
2906 // Copy the files into their new location.
2907 // If a prior process fataled copying or cleaning up files we tolerate any
2908 // of the existing files if they are identical to the ones being stored.
2909 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2910 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2911 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2912 if ( !$statusMove->isGood() ) {
2913 // Delete any files copied over (while the destination is still locked)
2914 $this->cleanupTarget( $triplets );
2915 $destFile->unlock();
2916 $this->file->unlock();
2917 wfDebugLog( 'imagemove', "Error in moving files: "
2918 . $statusMove->getWikiText( false, false, 'en' ) );
2919 $statusMove->ok = false;
2920
2921 return $statusMove;
2922 }
2923 $status->merge( $statusMove );
2924 }
2925
2926 // Rename the file versions metadata in the DB.
2927 $this->doDBUpdates();
2928
2929 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2930 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2931
2932 $destFile->unlock();
2933 $this->file->unlock(); // done
2934
2935 // Everything went ok, remove the source files
2936 $this->cleanupSource( $triplets );
2937
2938 $status->merge( $statusDb );
2939
2940 return $status;
2941 }
2942
2943 /**
2944 * Verify the database updates and return a new FileRepoStatus indicating how
2945 * many rows would be updated.
2946 *
2947 * @return FileRepoStatus
2948 */
2949 protected function verifyDBUpdates() {
2950 $repo = $this->file->repo;
2951 $status = $repo->newGood();
2952 $dbw = $this->db;
2953
2954 $hasCurrent = $dbw->selectField(
2955 'image',
2956 '1',
2957 [ 'img_name' => $this->oldName ],
2958 __METHOD__,
2959 [ 'FOR UPDATE' ]
2960 );
2961 $oldRowCount = $dbw->selectField(
2962 'oldimage',
2963 'COUNT(*)',
2964 [ 'oi_name' => $this->oldName ],
2965 __METHOD__,
2966 [ 'FOR UPDATE' ]
2967 );
2968
2969 if ( $hasCurrent ) {
2970 $status->successCount++;
2971 } else {
2972 $status->failCount++;
2973 }
2974 $status->successCount += $oldRowCount;
2975 // Bug 34934: oldCount is based on files that actually exist.
2976 // There may be more DB rows than such files, in which case $affected
2977 // can be greater than $total. We use max() to avoid negatives here.
2978 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
2979 if ( $status->failCount ) {
2980 $status->error( 'imageinvalidfilename' );
2981 }
2982
2983 return $status;
2984 }
2985
2986 /**
2987 * Do the database updates and return a new FileRepoStatus indicating how
2988 * many rows where updated.
2989 */
2990 protected function doDBUpdates() {
2991 $dbw = $this->db;
2992
2993 // Update current image
2994 $dbw->update(
2995 'image',
2996 [ 'img_name' => $this->newName ],
2997 [ 'img_name' => $this->oldName ],
2998 __METHOD__
2999 );
3000 // Update old images
3001 $dbw->update(
3002 'oldimage',
3003 [
3004 'oi_name' => $this->newName,
3005 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3006 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3007 ],
3008 [ 'oi_name' => $this->oldName ],
3009 __METHOD__
3010 );
3011 }
3012
3013 /**
3014 * Generate triplets for FileRepo::storeBatch().
3015 * @return array
3016 */
3017 protected function getMoveTriplets() {
3018 $moves = array_merge( [ $this->cur ], $this->olds );
3019 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3020
3021 foreach ( $moves as $move ) {
3022 // $move: (oldRelativePath, newRelativePath)
3023 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3024 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3025 wfDebugLog(
3026 'imagemove',
3027 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3028 );
3029 }
3030
3031 return $triplets;
3032 }
3033
3034 /**
3035 * Removes non-existent files from move batch.
3036 * @param array $triplets
3037 * @return Status
3038 */
3039 protected function removeNonexistentFiles( $triplets ) {
3040 $files = [];
3041
3042 foreach ( $triplets as $file ) {
3043 $files[$file[0]] = $file[0];
3044 }
3045
3046 $result = $this->file->repo->fileExistsBatch( $files );
3047 if ( in_array( null, $result, true ) ) {
3048 return Status::newFatal( 'backend-fail-internal',
3049 $this->file->repo->getBackend()->getName() );
3050 }
3051
3052 $filteredTriplets = [];
3053 foreach ( $triplets as $file ) {
3054 if ( $result[$file[0]] ) {
3055 $filteredTriplets[] = $file;
3056 } else {
3057 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3058 }
3059 }
3060
3061 return Status::newGood( $filteredTriplets );
3062 }
3063
3064 /**
3065 * Cleanup a partially moved array of triplets by deleting the target
3066 * files. Called if something went wrong half way.
3067 * @param array $triplets
3068 */
3069 protected function cleanupTarget( $triplets ) {
3070 // Create dest pairs from the triplets
3071 $pairs = [];
3072 foreach ( $triplets as $triplet ) {
3073 // $triplet: (old source virtual URL, dst zone, dest rel)
3074 $pairs[] = [ $triplet[1], $triplet[2] ];
3075 }
3076
3077 $this->file->repo->cleanupBatch( $pairs );
3078 }
3079
3080 /**
3081 * Cleanup a fully moved array of triplets by deleting the source files.
3082 * Called at the end of the move process if everything else went ok.
3083 * @param array $triplets
3084 */
3085 protected function cleanupSource( $triplets ) {
3086 // Create source file names from the triplets
3087 $files = [];
3088 foreach ( $triplets as $triplet ) {
3089 $files[] = $triplet[0];
3090 }
3091
3092 $this->file->repo->cleanupBatch( $files );
3093 }
3094 }
3095
3096 class LocalFileLockError extends ErrorPageError {
3097 public function __construct( Status $status ) {
3098 parent::__construct(
3099 'actionfailed',
3100 $status->getMessage()
3101 );
3102 }
3103
3104 public function report() {
3105 global $wgOut;
3106 $wgOut->setStatusCode( 429 );
3107 parent::report();
3108 }
3109 }